package org.apache.mina.protocol.dns.nameserver;

import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;

public class JvmConfiguration implements NameServerConfiguration {

    private boolean isOk = true;

    private List<SocketAddress> servers = new ArrayList<SocketAddress>();

    private List<String> domains = new ArrayList<String>();

    public JvmConfiguration() {
        try {
            Class<?>[] noClasses = new Class[0];
            Object[] noObjects = new Object[0];

            Class<?> clazz = Class.forName("sun.net.dns.ResolverConfiguration");

            // ResolverConfiguration resConf = ResolverConfiguration.open();
            Method open = clazz.getDeclaredMethod("open", noClasses);
            Object resConf = open.invoke(null, noObjects);

            // lserver_tmp = resConf.nameservers();
            Method nameservers = clazz.getMethod("nameservers", noClasses);
            List<?> nameServerNames = (List<?>) nameservers.invoke(resConf,
                    noObjects);

            // lsearch_tmp = resConf.searchlist();
            Method searchlist = clazz.getMethod("searchlist", noClasses);
            List<?> searchDomainNames = (List<?>) searchlist.invoke(resConf,
                    noObjects);

            for (Object obj : nameServerNames) {
                servers.add(new InetSocketAddress((String) obj, DNS_PORT));
            }

            for (Object obj : searchDomainNames) {
                domains.add((String) obj);
            }

        } catch (Exception e) {
            e.printStackTrace();
            isOk = false;
        }
    }

    /* (non-Javadoc)
     * @see org.apache.mina.protocol.dns.nameserver.NameServerConfiguration#getNameServers()
     */
    public List<SocketAddress> getNameServers() {
        return servers;
    }

    /* (non-Javadoc)
     * @see org.apache.mina.protocol.dns.nameserver.NameServerConfiguration#getDomains()
     */
    public List<String> getDomains() {
        return domains;
    }

    /* (non-Javadoc)
     * @see org.apache.mina.protocol.dns.nameserver.NameServerConfiguration#isOk()
     */
    public boolean isOk() {
        return isOk;
    }

}
